import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Store, select } from '@ngrx/store';
import { NzMessageService } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { SongService } from 'src/app/shared';
import { getPlayer, getCurrentSong } from 'src/app/store/selector/play.selector';
import { StoreActionService } from 'src/app/store/store-action.service';
import { AppStoreModule } from 'src/app/store/store.module';
import { SingerDetail, Song } from '../entity';

@Component({
  selector: 'app-singer-detail',
  templateUrl: './singer-detail.component.html',
  styleUrls: ['./singer-detail.component.less']
})
export class SingerDetailComponent implements OnInit, OnDestroy {

  singerDetail: SingerDetail;
  simiSingers: any;
  currentSong: Song;
  currentIndex = -1;

  private listenDestory = new Subject<void>();

  constructor(
    private activatedRoute: ActivatedRoute,
    private songService: SongService,
    private storeActionService: StoreActionService,
    private store$: Store<AppStoreModule>,
    private msg: NzMessageService
  ) { }

  ngOnInit(): void {
    this.activatedRoute.data.subscribe(({ singerDetail }) => {
      this.singerDetail = singerDetail;
    });
    this.listenCurrentSong();
  }

  ngOnDestroy(): void {
    this.listenDestory.next();
    this.listenDestory.complete();
  }

  onAddSongs(songs: Song[], isPlay = false): void {
    this.songService.getSongList(songs)
      .subscribe(list => {
        if (list && list.length > 0) {
          if (isPlay) {
            this.storeActionService.updatePlayList({ list, index: 0 });
          } else {
            this.storeActionService.insertSongs(list);
          }
        }
      });
  }

  onAddSong(song: Song, isPlay = false): void {
    if (this.canAddSong(this.currentSong, song)) {
      this.songService.getSongList(song).subscribe(
        list => {
          if (list && list.length > 0) {
            this.storeActionService.insertSong(list[0], isPlay);
          } else {
            this.msg.warning('无法播放该歌曲');
          }
        }
      );
    }
  }

  private listenCurrentSong(): void {
    this.store$.pipe(
      select(getPlayer),
      select(getCurrentSong),
      takeUntil(this.listenDestory))
      .subscribe(song => {
        this.currentSong = song;
        if (song) {
          this.currentIndex = this.singerDetail.hotSongs.findIndex(e => e.id === song.id);
        } else {
          this.currentIndex = -1;
        }
      });
  }

  private canAddSong(currentSong: Song, addSong: Song): boolean {
    return !currentSong || currentSong.id !== addSong.id;
  }

}
